#include "WmarkManager.h"

namespace camera::algorithm
{
    WmarkManager::WmarkManager()
    {
        ALOGI("%s ->", __func__);
        mWmarkDev = WmarkDev::getInstance();
        mWmarkDev->registerResultCallback(this);
        mDmaBufManager = new DmaBufManager();
        mWmarkBufManager = new WmarkBufManager();
        ALOGI("%s <-", __func__);
    }

    WmarkManager::~WmarkManager()
    {
    }

    void WmarkManager::onResult(wmark_buf_t &info)
    {
        int dmaBufIndex = -1;
        int warkBufIndex = -1;
        struct ion_buffer_info *dma_buf_info = NULL;
        WmarkBuf *wmark_buf_info = NULL;
        uint64_t copy_len = 0;

        mMutex.lock();

        dmaBufIndex = info.index;
        warkBufIndex = info.info.wmark_buf_id;
        ALOGD("%s %d: dma_buf_index=%d wmark_buf_index=%d", __func__, __LINE__, dmaBufIndex, warkBufIndex);

        if (mDmaBufManager)
        {
            dma_buf_info = mDmaBufManager->indexToBufAddr(dmaBufIndex);
        }

        if (mWmarkBufManager)
        {
            wmark_buf_info = mWmarkBufManager->getIndexWmarkBuf(warkBufIndex);
        }

        copy_len = info.info.picture.display.len;
        if (dma_buf_info && wmark_buf_info && wmark_buf_info->buf && dma_buf_info->buffer && (wmark_buf_info->bufMaxLen >= copy_len) && (dma_buf_info->buflen >= copy_len))
        {
            ALOGD("%s %d memcpy to wmark_buf  dstaddr=%p srcaddr=%p len=%ld", __func__, __LINE__, wmark_buf_info->buf, dma_buf_info->buffer, (unsigned long)copy_len);
            memcpy(wmark_buf_info->buf, dma_buf_info->buffer, copy_len);
            memcpy(&wmark_buf_info->property, &info, sizeof(wmark_buf_info->property));

            
            // for (int i = 0; i < 4; i++)
            // {
            //     dma_buf_info = mDmaBufManager->indexToBufAddr(i);
            //     ALOGD("dmabuf-index=%d", i);
            //     checkData(dma_buf_info->buffer, copy_len);
            // }

        }
        else
        {
            ALOGE("%s %d: error", __func__, __LINE__);
        }

        if (mWmarkDev)
        {
            mWmarkDev->setFreeWBufInfo(dmaBufIndex);
        }

        mMutex.unlock();
    }

    int WmarkManager::handle(algorithm_info_t &info)
    {
        // 这里用来处理， 每一个需要叠加的图像
        mMutex.lock();
        if (mWmarkBufManager)
        {
            mWmarkBufManager->hanlePngOverlay(info);
        }
        mMutex.unlock();
        return 0;
    }

    void WmarkManager::checkData(uint8_t *buffer, uint64_t len)
    {
        int i;
        unsigned char *ptr = (unsigned char *)buffer;
        int count = 0;

        if (!ptr)
        {
            fprintf(stderr, "<%s>: Invalid buffer...\n", __func__);
            return;
        }

        for (i = 0; i < len; i++) {
            if (ptr[i] != 0) {
                count++;
            }
        }

        ALOGD("%s %d : len = %lu !=0 cout=%d", __func__, __LINE__, (unsigned long) len, count);

        printf("\n");
    }
}